import { asyncRoutes, constantRoutes } from '@/router'

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * Use meta.role to determine if the current user has permission
 * @param roles_route
 * @param route
 */
function _hasPermission(roles_route, route) {
  if (roles_route) {
    return roles_route.some(path => route.path === path)
  } else {
    return false
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param role_routes
 */
export function _filterAsyncRoutes(routes, role_routes) {
  const res = []
  routes.forEach(route => {
    const tmp = { ...route }
    if (_hasPermission(role_routes, tmp)) {
      if (tmp.children) {
        tmp.children = _filterAsyncRoutes(tmp.children, role_routes)
      }
      res.push(tmp)
    } else if (route.meta.public) {
      res.push(tmp)
    }
  })

  return res
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({ commit }, roles_info) {
    return new Promise(resolve => {
      let accessedRoutes
      // 是否是超级管理员
      if (roles_info.roles.includes('1')) {
        accessedRoutes = asyncRoutes || []
      } else {
        accessedRoutes = _filterAsyncRoutes(asyncRoutes, roles_info.routes)
      }
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  }
  // generateRoutes({ commit }, roles) {
  //   return new Promise(resolve => {
  //     let accessedRoutes
  //     // 是否是超级管理员
  //     if (roles.includes(1)) {
  //       accessedRoutes = asyncRoutes || []
  //     } else {
  //       accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
  //     }
  //     commit('SET_ROUTES', accessedRoutes)
  //     resolve(accessedRoutes)
  //   })
  // }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
